package com.example.fengyungo.activity.me;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.example.fengyungo.R;
import com.example.fengyungo.activity.BaseActivity;
import com.example.fengyungo.constant.CodeConstant;
import com.example.fengyungo.constant.DriverConstant;
import com.example.fengyungo.constant.ResultConstant;
import com.example.fengyungo.constant.TextConstant;
import com.example.fengyungo.domain.Driver;
import com.example.fengyungo.domain.DriverVerify;
import com.example.fengyungo.utils.OkHttpUtils;
import com.example.fengyungo.utils.OssUtils;
import com.example.fengyungo.utils.PermissionUtil;
import com.example.fengyungo.utils.SharedPreferencesUtils;
import com.example.fengyungo.utils.ThreadPoolUtil;

import java.io.IOException;

/**
 * 司机实名认证的界面
 *
 * @author 徐
 */
public class VerifyActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "VerifyActivity";

    /**
     * 司机
     */
    Driver driver;
    /**
     * 司机状态
     */
    Integer status;
    /**
     * 认证结果
     */
    TextView verifyResultTv;
    /**
     * 返回
     */
    ImageButton backIb;
    /**
     * 确认提交
     */
    Button submitBtn;
    /**
     * 身份证人像面
     */
    ImageView idCardPeople;
    /**
     * 身份证国徽面
     */
    ImageView idCardEmblem;
    /**
     * 人手持身份证
     */
    ImageView idCardWithPeople;
    /**
     * 驾驶证
     */
    ImageView driverCard;
    /**
     * 当前选择的图片类型
     */
    int currentImage;
    /**
     * 身份证人像面
     */
    private static final int ID_CARD_PEOPLE = 0;
    /**
     * 身份证国徽面
     */
    private static final int ID_CARD_EMBLEM = 1;
    /**
     * 人手持身份证
     */
    private static final int ID_CARD_WITH_PEOPLE = 2;
    /**
     * 驾驶证照片
     */
    private static final int DRIVER_CARD = 3;
    /**
     * 当前选择的图片的路径
     */
    String picturePath;
    /**
     * 身份证人像面路径
     */
    String idCardPeoplePath;
    /**
     * 身份证国徽面路径
     */
    String idCardEmblemPath;
    /**
     * 手持身份证照片路径
     */
    String idCardWithPeoplePath;
    /**
     * 驾驶证照片路径
     */
    String driverCardPath;
    /**
     * 姓名输入框
     */
    EditText nameEt;
    /**
     * 身份证号输入框
     */
    EditText idCardEt;
    /**
     * 真实姓名
     */
    String name;
    /**
     * 身份证号
     */
    String idCard;
    /**
     * 加载中
     */
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify);

        verifyResultTv = findViewById(R.id.tv_verify_result);
        backIb = findViewById(R.id.back);
        idCardPeople = findViewById(R.id.img_id_card_people);
        idCardEmblem = findViewById(R.id.img_id_card_emblem);
        idCardWithPeople = findViewById(R.id.img_id_card_with_people);
        driverCard = findViewById(R.id.img_card_driver);
        submitBtn = findViewById(R.id.btn_submit);
        nameEt = findViewById(R.id.et_name);
        idCardEt = findViewById(R.id.et_id_card);
        progressBar = findViewById(R.id.progress_bar);

        // 设置点击事件
        backIb.setOnClickListener(this);
        idCardPeople.setOnClickListener(this);
        idCardEmblem.setOnClickListener(this);
        idCardWithPeople.setOnClickListener(this);
        driverCard.setOnClickListener(this);
        submitBtn.setOnClickListener(this);

        // 获取司机信息
        driver = SharedPreferencesUtils.getDriverInfo(this);
        // 获取司机实名状态
        status = driver.getStatus();

        LinearLayout linearLayout = findViewById(R.id.linear_verify);

        // 根据不同的认证情况展示不同的提示信息
        if (status == DriverConstant.VERIFIED) {
            // 已实名认证
            verifyResultTv.setVisibility(View.VISIBLE);
            linearLayout.setVisibility(View.INVISIBLE);
        } else if (status == DriverConstant.VERIFYING) {
            // 正在认证中
            verifyResultTv.setVisibility(View.VISIBLE);
            verifyResultTv.setText(TextConstant.VERIFYING);
            linearLayout.setVisibility(View.INVISIBLE);
        }
        // 还没有认证则不做处理
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: resultCode=" + resultCode);
        if (requestCode == CodeConstant.SELECT_PHOTO) {
            if (resultCode == RESULT_OK && data != null) {
                Uri selectedImage = data.getData();
                Log.d(TAG, "onActivityResult: selectedImage=" + selectedImage);
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                Log.d(TAG, "onActivityResult: picturePath=" + picturePath);

                // 刷新，设置图片
                Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
                // 根据不同情况进行设置
                if (currentImage == ID_CARD_PEOPLE) {
                    // 人像
                    idCardPeople.setImageDrawable(drawable);
                    idCardPeoplePath = picturePath;
                } else if (currentImage == ID_CARD_EMBLEM) {
                    // 国徽
                    idCardEmblem.setImageDrawable(drawable);
                    idCardEmblemPath = picturePath;
                } else if (currentImage == ID_CARD_WITH_PEOPLE) {
                    // 手持
                    idCardWithPeople.setImageDrawable(drawable);
                    idCardWithPeoplePath = picturePath;
                } else if (currentImage == DRIVER_CARD) {
                    // 驾驶
                    driverCard.setImageDrawable(drawable);
                    driverCardPath = picturePath;
                }
            }
        }
    }

    /**
     * 将司机认证信息存到服务端数据库
     */
    private void addDriverVerify() {
        progressBar.setVisibility(View.VISIBLE);
        Runnable runnable = () -> {
            try {
                String url = DriverConstant.URL_USER_DRIVER + "/addDriverVerify";
                DriverVerify driverVerify = new DriverVerify();
                driverVerify.setDriverId(driver.getId());
                driverVerify.setName(name);
                driverVerify.setIdCard(idCard);
                driverVerify.setDriverCard(OssUtils.generateOssUrl(this, driverCardPath));
                driverVerify.setIdCardEmblem(OssUtils.generateOssUrl(this, idCardEmblemPath));
                driverVerify.setIdCardPeople(OssUtils.generateOssUrl(this, idCardPeoplePath));
                driverVerify.setIdCardWithPeople(OssUtils.generateOssUrl(this, idCardWithPeoplePath));
                String json = JSONObject.toJSONString(driverVerify);
                String responseData = OkHttpUtils.post(url, json);
                Log.d(TAG, "addDriverVerify: responseData=" + responseData);
                JSONObject jsonObject = JSONObject.parseObject(responseData);
                int code = jsonObject.getInteger(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                if (code == ResultConstant.SUCCESS) {
                    Log.d(TAG, "addDriverVerify: success");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.GONE);
                            Toast.makeText(VerifyActivity.this, TextConstant.UPLOAD_SUCCESS, Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.GONE);
                            Toast.makeText(VerifyActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(VerifyActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            // 身份证人像面
            case R.id.img_id_card_people:
                openAlbum(ID_CARD_PEOPLE);
                Log.d(TAG, "onClick: currentImage=" + currentImage);
                break;
            // 身份证国徽面
            case R.id.img_id_card_emblem:
                openAlbum(ID_CARD_EMBLEM);
                Log.d(TAG, "onClick: currentImage=" + currentImage);
                break;
            // 手持身份证
            case R.id.img_id_card_with_people:
                openAlbum(ID_CARD_WITH_PEOPLE);
                Log.d(TAG, "onClick: currentImage=" + currentImage);
                break;
            // 驾驶证
            case R.id.img_card_driver:
                openAlbum(DRIVER_CARD);
                Log.d(TAG, "onClick: currentImage=" + currentImage);
                break;
            case R.id.btn_submit:
                // 确认四张图都有了
                if (idCardPeoplePath == null || idCardEmblemPath == null
                        || idCardWithPeoplePath == null || driverCardPath == null) {
                    Toast.makeText(this, TextConstant.IMAGE_NOT_ALL_SELECTED, Toast.LENGTH_SHORT).show();
                    break;
                }
                Log.d(TAG, "onActivityResult: idCardPeoplePath="+idCardPeoplePath);
                Log.d(TAG, "onActivityResult: idCardEmblemPath="+idCardEmblemPath);
                Log.d(TAG, "onActivityResult: idCardWithPeoplePath="+idCardWithPeoplePath);
                Log.d(TAG, "onActivityResult: driverCardPath="+driverCardPath);
                // 获取姓名和身份证号
                name = nameEt.getText().toString();
                idCard = idCardEt.getText().toString();
                // 存到服务端数据库
                addDriverVerify();
                // 上传图片
                OssUtils.upload(this, OssUtils.getFilename(this,idCardPeoplePath), idCardPeoplePath);
                OssUtils.upload(this, OssUtils.getFilename(this,idCardEmblemPath), idCardEmblemPath);
                OssUtils.upload(this, OssUtils.getFilename(this,idCardWithPeoplePath), idCardWithPeoplePath);
                OssUtils.upload(this, OssUtils.getFilename(this,driverCardPath), driverCardPath);
                // 修改司机状态为审核中
                SharedPreferencesUtils.setDriverInfoToSharedPreferences(this, DriverConstant.STATUS,DriverConstant.VERIFYING);
                break;
            default:
                break;
        }
    }

    /**
     * 打开相册
     *
     * @param imageType 要选择的图片类型：人像、国徽、手持、驾驶
     */
    private void openAlbum(int imageType) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 动态获取权限
            PermissionUtil.getPermission(this);
            return;
        }
        // 设置选择的照片类型
        currentImage = imageType;
        //Intent.ACTION_PICK 从数据中选择一个项目 (item)，将被选中的项目返回。
        //MediaStore.Images.Media.EXTERNAL_CONTENT_URI 获取外部的URI
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        //参数一:对应的数据的URI 参数二:使用该函数表示要查找文件的MIME类型
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, CodeConstant.SELECT_PHOTO);
    }
}